<template>


  <el-form :model="user" label-width="auto">
    <el-row>
      <el-col :span="12">
        <el-form-item prop="nickname" label="昵称">
          <el-input v-model="user.nickname" disabled></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="user.username" disabled></el-input>
        </el-form-item>
      </el-col>
    </el-row>

  </el-form>
  <el-table :data="roleList" @selection-change="newSelect" ref="tableRef" row-key="id">
    <el-table-column type="selection" label="选择" width="100"></el-table-column>
    <el-table-column type="index" label="序号" width="200"></el-table-column>
    <el-table-column prop="roleName" label="角色名称" width="300"></el-table-column>
  </el-table>


  <el-button @click="save">确定</el-button>

</template>


<script setup name="">

import {getRoleList, grant} from '@/api/permission/user'
import {nextTick, onMounted, ref} from "vue";
import {ElNotification} from "element-plus";

//定义的属性数据 :closeDialog="closeUserRoleDialog" :userId="userId"
const {closeDialog, userId} = defineProps(['closeDialog', 'userId'])

//表格引用对象 用于设置选中 的
const tableRef = ref()
//角色表格数据
const roleList = ref([])
// 选中的角色id
let selectRoleIds = []

//当前授权的用户信息
const user = ref({})


function save() {
  console.log("selectRoleIds")
  console.log(selectRoleIds)

  // closeDialog();
  grant(userId, selectRoleIds).then(success => {
    if (success) {
      ElNotification({
        title: '消息',
        type: 'success',
        message: "授权成功",
      })

      //调用父组件中的 函数用于关闭 dialog 和更新查询结果
      closeDialog()
    }
  })
}


/**当表格选中发变化
 * @param newSelection
 */
function newSelect(newSelection) {
  selectRoleIds = []

  // console.log("newSelection",newSelection)
  // allSelection.value = allSelection;
  newSelection.forEach((item) => {
    selectRoleIds.push(item.id)
  })
}

//查询所有角色列表
onMounted(() => {
  getRoleList(userId).then((data) => {

    //当前用户信息
    user.value = data.user;

    //所有角色列表
    roleList.value = data.roleList;


    //勾选已经授权的角色
    const {userRoleList} = data
    nextTick(() => {
      //循环所有用户已经有的角色
      userRoleList.forEach(row => {
        tableRef.value?.toggleRowSelection(row) // 设置勾选
      })
    })

  })
})

</script>


<style>

</style>